package main

import (
	"fmt"
	"hello/ctrl"
	"html/template"
	"log"
	"net/http"
	"strings"
)

func RegisterTemplate() {
	//全局扫描模板
	GlobTemplate := template.New("root")
	GlobTemplate, err := GlobTemplate.ParseGlob("view/**/*")
	if err != nil {
		//打印错误信息
		//退出系统
		log.Fatal(err)
	}
	//分别对每一个模板进行注册
	for _, tpl := range GlobTemplate.Templates() {
		pattern := tpl.Name()
		http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
			_ = GlobTemplate.ExecuteTemplate(w, pattern, nil)
		})
		fmt.Println("register=>" + pattern)
	}
}
func RegisterView() {
	//一次解析出全部模板
	tpl, err := template.ParseGlob("view/**/*.html")
	if nil != err {
		log.Fatal("解析模版出错:", err)
	}
	//通过for循环做好映射
	for _, v := range tpl.Templates() {
		tplName := v.Name()
		if strings.HasPrefix(tplName, "/") {
			fmt.Println("HandleFunc     ", tplName)
			http.HandleFunc(tplName, func(w http.ResponseWriter, request *http.Request) {
				fmt.Println("parse     " + tplName + "==" + tplName)
				err := tpl.ExecuteTemplate(w, tplName, nil)
				if err != nil {
					log.Fatal(err.Error())
				}
			})
		}
	}
}

func main() {
	//绑定请求和处理函数
	http.HandleFunc("/user/login", ctrl.UserLogin)
	http.HandleFunc("/user/register", ctrl.UserRegister)

	//1 提供静态资源目录支持
	//http.Handle("/", http.FileServer(http.Dir(".")))

	//2 指定目录的静态文件
	http.Handle("/asset/", http.FileServer(http.Dir("../")))

	RegisterView()

	_ = http.ListenAndServe(":8080", nil)
}
